#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
#include <cstring>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>

#define MAXARGC 128
std::vector<std::string> Commands;
char *g_argv[MAXARGC];

void PrintCommandLine()
{
    const char *pwd = getenv("PWD");
    const char *user = getenv("USER");
    std::cout << user << "@hcss-ecs-7369:~" << pwd << "#";
}

void conductComandLine()
{
    std::string clientCommand;
    getline(std::cin, clientCommand);
    clientCommand.push_back(' ');
    size_t old_pos = 0;
    size_t pos;
    while (true)
    {
        pos = clientCommand.find(" ", old_pos);
        if (pos != std::string::npos)
        {
            std::string cur(clientCommand.begin() + old_pos, clientCommand.begin() + pos);
            if (cur.empty())
            {
                old_pos = pos + 1;
            }
            else
                Commands.push_back(cur);
        }
        else
            break;
        old_pos = pos + 1;
    }
    std::string s("hello");
    // strcpy(g_argv[0], s.c_str());
    int n = Commands.size();
    for (int i = 0; i < n; i++)
    {
        g_argv[i] = (char *)malloc(sizeof(Commands[i].size()) + 1);
        strcpy(g_argv[i], Commands[i].c_str());
    }
    g_argv[n] = NULL;
}

void excuteCommand()
{
    pid_t id = fork();
    if (id == 0)
    {
        // child
        execvp(g_argv[0], g_argv);
        exit(1);
    }

    // father
    pid_t rid = waitpid(id, nullptr, 0);
    Commands.clear();
    (void)rid; // rid使用一下
}

int main()
{
    while (true)
    {
        // 1,打印命令行并保存
        PrintCommandLine();

        // 2.处理输入的命令行
        conductComandLine();
        // for (auto &x : Commands)
        // {
        //     std::cout << x << " ";
        // }
        // std::cout << std::endl;

        // 3.执行命令
        excuteCommand();
    }
    return 0;
}